<template>
  <div class="home-container">
    <div class="left-container box-shadow">
      <el-tabs v-model="activeName" @tab-click="handleTabsClick" class="left-tabs">
        <el-tab-pane label="我的资料" name="first" class="tab-panel">
          <el-form :model="informationData"
                   :rules="rules"
                   ref="userInfoForm"
                   class="left-form"
                   label-width="80px">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="informationData.gender">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="informationData.phone" placeholder="输入手机号" style="width: 220px"></el-input>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="informationData.birthday"
                type="date"
                value-format="timestamp"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="家籍地址" prop="address" required>
              <el-cascader
                v-model="informationData.address"
                :options="addressOptions"
                :props="{ expandTrigger: 'hover' }"
                filterable
                @change="handleChange"></el-cascader>
            </el-form-item>
            <el-form-item label="个人愿望" prop="wish">
              <el-input type="textarea" v-model="informationData.wish" placeholder="写下你的小愿望吧~" maxlength="120" resize="none" rows="3"></el-input>
            </el-form-item>
            <el-form-item style="text-align: right">
              <el-button type="primary" @click="updateUserInfoClick">更新</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改邮箱" name="second" class="tab-panel">
          <el-steps :active="emailActive" finish-status="success" direction="vertical" align-center class="email-steps">
            <el-step icon="el-icon-unlock" title="开始"></el-step>
            <el-step icon="el-icon-time" title="进行中"></el-step>
            <el-step icon="el-icon-lock" title="完成"></el-step>
          </el-steps>
          <el-form class="email-form" label-width="80px" :rules="emailRules" ref="emailForm" :model="updateEmail" v-if="emailActive === 0">
            <h3>解除原邮箱</h3>
            <el-form-item label="邮箱" prop="email">
              <el-input style="width: 300px;" v-model="updateEmail.email" disabled></el-input>
            </el-form-item>
            <el-form-item label="验证" prop="code">
              <el-input placeholder="输入邮箱验证码" v-model="updateEmail.code" style="width: 300px">
                <template slot="append">
                  <div style="width: 80px;">
                    <el-button @click="sendEmail" v-show="isSend" style="color:#409EFF">发送验证码</el-button>
                    <span ref="appendMail"></span>
                  </div>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="unbindEmail">下一步</el-button>
            </el-form-item>
          </el-form>
          <el-form class="email-form" label-width="80px" :rules="emailRules" ref="emailForm" :model="updateEmail" v-else-if="emailActive === 1">
            <h3>绑定新邮箱</h3>
            <el-form-item label="邮箱" prop="email">
              <el-input placeholder="输入新邮箱" v-model="updateEmail.email" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="验证" prop="code">
              <el-input placeholder="输入邮箱验证码" v-model="updateEmail.code" required style="width: 300px">
                <template slot="append">
                  <div style="width: 80px;">
                    <el-button @click="sendEmail" v-show="isSend" style="color:#409EFF">发送验证码</el-button>
                    <span ref="appendMail"></span>
                  </div>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="bindEmail">下一步</el-button>
            </el-form-item>
          </el-form>
          <el-form class="email-form" v-else-if="emailActive === 2">
            <el-form-item>
              <p class="email-end-text">邮箱修改成功！</p>
            </el-form-item>
            <el-form-item>
              <el-link @click="emailActive = 0" :underline="false">返回</el-link>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="third">
          <el-form
            ref="pwdForm"
            :rules="pwdRules"
            :model="updatePwd"
            label-width="80px"
            style="width:400px;margin: 50px auto;">
            <el-form-item label="旧密码" prop="old">
              <el-input v-model="updatePwd.old" placeholder="请输入您的当前密码" autocomplete="off" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new">
              <el-input v-model="updatePwd.new" placeholder="请设置您的新密码" autocomplete="off" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="check">
              <el-input v-model="updatePwd.check" placeholder="请再次确认您的密码" autocomplete="off" show-password></el-input>
            </el-form-item>
            <el-form-item style="text-align: right;">
              <el-button type="primary" @click="submitUpdatePwd">确认</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="right-container box-shadow">
      <div class="right-head">
        <div class="avatar-box"
             @mouseover.stop="uploadAvatarActive = true"
             @mouseout.stop="uploadAvatarActive = false">
          <transition name="avatar">
            <el-avatar icon="el-icon-user-solid" :size="120" v-if="!uploadAvatarActive" :src="userShow.avatar"/>
            <el-upload v-else
              action=""
              :show-file-list="false"
              :on-change="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"><div class="upload">点击上传</div></el-upload>
          </transition>
        </div>
        <dialog-cropper :img="cropImg" :isVisible="cropVisible" @get="getFileData" @close="closeDialog" />
      </div>
      <div class="right-main">
        <div class="name">{{ userShow.name }}</div>
        <div>{{ userShow.position }}·{{ userShow.department }}</div>
        <div class="seniority">{{ userShow.createtime | unixTimeToIntervalDate }}</div>
      </div>
    </div>
  </div>
</template>

<script>
  import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
  import DialogCropper from '@/components/cropper'
  import { getUserInfo, uploadAvatar } from '@/api/user'
  import {bindEmail, sendEmail, unbindEmail, updatePassword, updateUserInfo} from "../../api/user";

    export default {
      name: "home",
      components: { DialogCropper },
      data() {
        //自定义级联选择器校验
        let checkAddress = (rule, value, callback) => {
          if(value[0] === null || value.length === 0 || value === '' || value === null) {
            return callback(new Error('请输入家籍地址'))
          }else {
            callback();
          }
        };
        //自定义确认密码校验
        let checkPwd = (rule, value, callback)=>{
          if(value == '') {
            callback(new Error('请再次输入您的密码'));
          }else if(value !== this.updatePwd.new) {
            callback(new Error('两次输入密码不一致'));
          }else {
            callback();
          }
        };
        return {
          rules: {
            gender: [{required: true, message: '请选择性别', trigger: 'change'}],
            phone: [{required: true, message: '请输入手机号码', trigger: 'blur'}],
            birthday: [{required: true, message: '请输入出生日期', trigger: 'blur'}],
            // address: [{required: true, message: '请输入家籍地址', type: 'array', trigger: 'blur'}],
            address: [{ validator: checkAddress, trigger: 'blur'}],
            wish: [{required: false, message: '请输入个人心愿', trigger: 'blur'}]
          },
          emailRules: {
            email: [{ required: true, message: '请输入绑定的邮箱', trigger: 'blur' }, { type: 'email', message: '邮箱格式不合法', trigger: 'blur' }],
            code: [{ required: true, message: '请输入邮箱验证码', trigger: 'blur' }]
          },
          informationData: {
            gender: 0,
            birthday: '',
            address: '',
            wish: ''
          },
          activeName: 'first',
          addressOptions: regionData,
          emailActive: 0,
          updateEmail: {
            email: '',
            code: ''
          },
          flag: '',
          isSend: true,
          uploadAvatarActive: false,
          cropImg: '',
          cropVisible: false,
          userShow: {
            avatar: '',
            name: '',
            position: '',
            department: '',
            createtime: ''
          },
          pwdRules: {
            old: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
            new: [{ required: true, message: '请设置新密码', trigger: 'blur' }],
            check: [{ validator: checkPwd, required: true, trigger: 'blur' }]
          },
          updatePwd: {
            old: '',
            new: '',
            check: ''
          }
        }
      },
      mounted() {
        this.initUserInfo();
      },
      methods: {
        //初始化获取用户个人信息
        initUserInfo() {
          getUserInfo().then(res=>{
            let userinfo = res.data.data.user_info;
            this.informationData = {
              gender: userinfo.gender,
              phone: userinfo.phone,
              birthday: userinfo.birthday,
              address: userinfo.address,
              wish: userinfo.wish
            }
            this.userShow = {
              avatar: userinfo.avatar,
              name: userinfo.name,
              position: userinfo.positionName,
              department: userinfo.departmentName,
              createtime: userinfo.createtime
            }
            this.updateEmail.email = userinfo.email
          })
        },
        //点击更新用户个人信息
        updateUserInfoClick() {
          this.$refs['userInfoForm'].validate(valid =>{
            if(valid) {
              let data = this.informationData;
              updateUserInfo(data).then(res=>{
                let code = res.data.code
                if(code === 200) this.$message.success(res.data.message)
              }, {})
            }
          })
        },
        //发送验证码按钮判断
        sendEmail() {
          if(this.emailActive === 1) {
            this.$refs['emailForm'].validateField('email', (errorMsg) => {
              if(errorMsg) {
                console.log('邮箱不合法');
              }else {
                this.sendEmailCode()
              }
            })
          }else {
            this.sendEmailCode()
          }
        },
        //发送验证码请求
        sendEmailCode() {
          sendEmail(this.updateEmail.email).then(res=>{
            if(res.data.code === 200) {
              let time = 120;
              this.flag = setInterval(()=>{
                if(time) this.isSend = false;
                this.$refs.appendMail.innerText = `重新发送(${--time})`;
                if(time < 0) {
                  clearInterval(this.flag);
                  this.$refs.appendMail.innerText = ''
                  this.isSend = true;
                }
              }, 1000)
            }
          })
        },
        //解绑原邮箱
        unbindEmail() {
          this.$refs['emailForm'].validate(valid=>{
            if(valid) {
              unbindEmail(this.updateEmail).then(res=>{
                if(res.data.code === 200) {
                  this.$cookies.set('bind_token', res.data.data.bind_mail_token, '5min')
                  this.emailActive ++;
                  this.updateEmail.email = '';
                  this.updateEmail.code = '';
                  clearInterval(this.flag);
                  this.$refs.appendMail.innerText = '';
                  this.isSend = true;
                }
              })
            }
          })
        },
        //绑定新邮箱
        bindEmail() {
          this.$refs['emailForm'].validate(valid=>{
            if(valid) {
              bindEmail(this.updateEmail).then(res=>{
                if(res.data.code === 200) {
                  this.emailActive ++;
                  this.updateEmail.code = ''
                  clearInterval(this.flag);
                  this.$refs.appendMail.innerText = '';
                  this.isSend = true;
                }
              })
            }
          })
        },
        //修改密码
        submitUpdatePwd() {
          let data = {
            oldPassword: this.updatePwd.old,
            newPassword: this.updatePwd.new
          }
          this.$refs['pwdForm'].validate(valid=>{
            if(valid) {
              updatePassword(data).then(res=> {
                if (res.data.code === 200) {
                  this.$message.success(res.data.message)
                  this.$refs['pwdForm'].resetFields();
                }
              })
            }
          })
        },
        //tabs点击监听,做一些初始化
        handleTabsClick() {
          emailActive : 0
        },
        //地区级联监听
        handleChange() {
          console.log(this.informationData.address)
          let addressArray = []
            this.informationData.address.filter(item => {
            addressArray.push(CodeToText[item])
          })
          console.log(addressArray)
        },
        //监听头像file上传
        handleAvatarSuccess(file) {
          this.cropImg = URL.createObjectURL(file.raw);
          this.cropVisible = true;
        },
        //头像选择前钩子，判断图片类型大小
        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024 / 1024 < 2;

          if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
          }
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isJPG && isLt2M;
        },
        //关闭上传回调
        closeDialog() {
          this.cropImg = '';
          this.cropVisible = false;
        },
        //获取截图base，并上传
        getFileData(data) {
          uploadAvatar(data).then(res=>{
            if(res.data.code === 200) {
              this.userShow.avatar = data;
              this.$store.commit('setAvatar', data)
            }
          })
        }
      }
    }
</script>

<style lang="scss" scoped>
  .home-container {
    background-color: #fff;
    min-height: 600px;
    padding: 20px;

    .left-container {
      min-height: 500px;
      width: 58%;
      float: left;
      .left-tabs {
        margin: 0 20px;
        .tab-panel {
          display: inline-block;
          width: 100%;
        }
        .left-form {
          text-align: left;
          margin: 10px;
        }
      }
      .email-steps {
        height: 350px;
        width: 20%;
        margin: 10px 0 0 20px;
        padding-top: 30px;
        border-right: 2px #EBEEF5 solid;
        float: left;
      }
      .email-form {
        width: 70%;
        margin: 20px auto;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        flex-flow: column;
        overflow-x: hidden;
        h3 {
          display: block;
          width: 100%;
          position: relative;
          padding-bottom: 10px;
          margin-bottom: 20px;
          text-align: left;
          color:#909399
        }
        .email-end-text {
          margin-top: 60px;
          font-size: 20px;
          font-weight: 600;
          color: #F56C6C;
        }
      }
    }
    .right-container {
      min-height: 500px;
      width: 39%;
      float: right;

      .right-head {
        padding: 60px 0 50px 0;
        min-height: 150px;
        .avatar-box {
          border: 1px #A9A9A9 solid;
          border-radius: 100%;
          width: 120px;
          height: 120px;
          margin: 0 auto;
          overflow: hidden;
          .upload {
            width: 120px;
            height: 120px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 100%;
            background-color: #fff;
            color: #253243;
          }
          .avatar-enter,
          .avatar-leave-to {
            opacity: 0;
            transform: rotate3d(0, 0, 40, 180deg);
          }
          .avatar-enter-active,
          .avatar-leave-active {
            transition: all 0.6s ease-in-out;
          }
        }
      }
      .right-main {
        padding: 20px;
        div + div {
          margin-top: 20px;
        }
        div {
          color: #AAA;
        }
        .name {
          margin-bottom: 70px;
          font-weight: 600;
          color: #253243;
          font-size: 18px;
          letter-spacing: 3px;
          font-family: Avenir, Helvetica Neue, Arial, Helvetica, sans-serif;
        }
        .seniority {
          color: #292929;
        }
      }
    }
  }
</style>
